<?php

namespace app\index\controller\wanlshop;

use app\admin\model\SeparateVideo;
use app\admin\model\Store;
use app\admin\model\StoreSub;
use app\api\model\SeparateSet;
use app\common\controller\Wanlshop;
use app\common\model\Area;
use app\index\model\wanlshop\ShopConfig;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use wechat\WechatController;

class Separate extends Wanlshop
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new StoreSub();
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("typeList", $this->model->getTypeList());
    }

    /**
     * 类目管理
     */
    public function accounts()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch('wanlshop/separate/accounts');
    }
    public function group(){
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            $this->model = new \app\admin\model\Group();
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch('wanlshop/separate/group');
    }
    public function add(){
        //设置过滤方法
        $this->request->filter(['']);
        if ($this->request->isPost()) {
            $params = $this->request->param("row/a");
            $shop_config = ShopConfig::get(['shop_id'=>$this->shop->id]);
            $service_secret = $shop_config->service_secret;
            $sub_mch_id = $shop_config->sub_mch_id;
            $store = Store::get(['sub_mch_id'=>$sub_mch_id]);
            $params['service_secret'] = $service_secret;
            $params['shop_id'] = $this->shop->id;
            $params['store_id'] = $store->id;
            $secret = SeparateSet::get(['secret'=>$service_secret]);
            $wechat = new WechatController($sub_mch_id,$secret);
            $res = $wechat->addReceiverOpenid($params);
            if ($res['result_code'] == "FAIL") {
                $this->error($res['err_code_des']);
            }
            $this->model->allowField(true)->save($params);
            $this->success("添加成功");
        }
        return $this->view->fetch();
    }
    public function group_add(){
        $this->request->filter(['']);
        if ($this->request->isPost()) {
            $this->model = new \app\admin\model\Group();
            $shop_config = ShopConfig::get(['shop_id'=>$this->shop->id]);
            $service_secret = $shop_config->service_secret;
            $sub_mch_id = $shop_config->sub_mch_id;
            $store = Store::get(['sub_mch_id'=>$sub_mch_id]);
            $params = $this->request->param('row/a');
            $params['service_secret'] = $service_secret;
            $params['shop_id'] = $this->shop->id;
            $params['store_id'] = $store->id;
            $this->model->allowField(true)->save($params);
            $this->success("添加成功");
        }
        return $this->view->fetch();
    }
    public function group_edit($ids = null){
        $this->model = new \app\admin\model\Group();
        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            $params = $this->request->param('row/a');
            $row->allowField(true)->save($params);
            $this->success("修改成功");
        }
        $this->assign("row",$row);
        return $this->view->fetch();
    }
    public function edit($ids = null){
        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            $params = $this->request->param('row/a');
            $shop_config = ShopConfig::get(['shop_id'=>$this->shop->id]);
            $service_secret = $shop_config->service_secret;
            $sub_mch_id = $shop_config->sub_mch_id;
            $secret = SeparateSet::get(['secret'=>$service_secret]);
            $wechat = new WechatController($sub_mch_id,$secret);
            $res = $wechat->addReceiverOpenid($params);
            if ($res['result_code'] == "FAIL") {
                $this->error($res['err_code_des']);
            }
            $row->allowField(true)->save($params);
            $this->success("修改成功");
        }
        $area = Area::get($row->area);
        $mergename = explode(",",$area->mergename);
        $row['province_name'] = $row['city_name'] = $row['area_name'] = "";
        if (!empty($mergename[1]))
        $row['province_name'] = $mergename[1];
        if (!empty($mergename[2]))
        $row['city_name'] = $mergename[2];
        if (!empty($mergename[3]))
        $row['area_name'] = $mergename[3];
        $this->assign("row",$row);
        return $this->view->fetch();
    }
    public function group_del($ids = null){
        $this->model = new \app\admin\model\Group();
        $this->extracted($ids);
    }
    public function video(){
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            $this->model = new SeparateVideo();
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch('wanlshop/separate/group');
    }
    public function video_add(){
        $this->request->filter(['']);
        if ($this->request->isPost()) {
            $this->model = new SeparateVideo();
            $shop_config = ShopConfig::get(['shop_id'=>$this->shop->id]);
            $service_secret = $shop_config->service_secret;
            $sub_mch_id = $shop_config->sub_mch_id;
            $store = Store::get(['sub_mch_id'=>$sub_mch_id]);
            $params = $this->request->param('row/a');
            $params['service_secret'] = $service_secret;
            $params['shop_id'] = $this->shop->id;
            $params['store_id'] = $store->id;
            $this->model->allowField(true)->save($params);
            $this->success("添加成功");
        }
        return $this->view->fetch();
    }
    public function video_edit($ids = null){
        $this->model = new SeparateVideo();
        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            $params = $this->request->param('row/a');
            $row->allowField(true)->save($params);
            $this->success("修改成功");
        }
        $this->assign("row",$row);
        return $this->view->fetch();
    }
    public function store_list(){
        $this->model = new \app\admin\model\Group();
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $total = $this->model
            ->where($where)
            ->order($sort, $order)
            ->count();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();
        $list = collection($list)->toArray();
        $result = array("total" => $total, "rows" => $list);
        return json($result);
    }
    public function del($ids = null){
        $this->extracted($ids);
    }
    public function video_del($ids = null){
        $this->model = new SeparateVideo();
        $this->extracted($ids);
    }

    /**
     * @param $ids
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function extracted($ids): void
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $this->model->where('shop_id', '=', $this->shop->id);
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success("删除成功");
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}